package com.awplanet.sitegen.template;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * User: a_polyakov
 */
public class Template extends AbstractTemplate {

	private List<AbstractTemplate> list = new ArrayList<AbstractTemplate>();

	public Template(String text) {
		int attrEnd = 0;
		int attrBegin = text.indexOf("${", attrEnd);
		while (attrBegin >= 0) {
			AbstractTemplate item = new StringTemplate(text.substring(attrEnd, attrBegin));
			list.add(item);
			attrEnd = text.indexOf("}", attrBegin + 2);
			if (attrEnd > attrBegin) {
				String attrName = text.substring(attrBegin + 2, attrEnd);
				item = new AttrTemplate(attrName);
				list.add(item);
			} else
				throw new RuntimeException("Error template format");
			attrEnd++;
			attrBegin = text.indexOf("${", attrEnd);
		}
		if (attrEnd < text.length()) {
			AbstractTemplate item = new StringTemplate(text.substring(attrEnd));
			list.add(item);
		}
	}

	public int indexAttr(String attrName) {
		int index = -1;
		for (int i = 0; index < 0 && i < list.size(); i++) {
			final AbstractTemplate item = list.get(i);
			if (item instanceof AttrTemplate) {
				final AttrTemplate itemAttr = (AttrTemplate) item;
				if (itemAttr.getName().equals(attrName)) {
					index = i;
				}
			}
		}
		return index;
	}

	@Override
	public void write(OutputStream outputStream, Map<String, String> attrs, Map<String, Object> hideAttr) throws IOException {
		for (AbstractTemplate item : list) {
			item.write(outputStream, attrs, hideAttr);
		}
	}
}
